package com.shark.security.jwt.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.shark.security.jwt.constant.RedisConstant;
import com.shark.security.jwt.utils.JwtTokenUtil;
import com.shark.security.jwt.utils.RedisUtil;

/**
 *拦截请求，解码jwt Token
 * @author junxiao
 *
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setHeader("Access-Control-Allow-Headers", "*");
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(tokenHead)) {
            final String authToken = authHeader.substring(tokenHead.length()); // The part after "Bearer "
            String username = jwtTokenUtil.getUsernameFromToken(authToken);

            Object sessionToken = RedisUtil.get(RedisConstant.User_Login_Token + username);
            if (StringUtils.isEmpty(sessionToken)
                    || !sessionToken.toString().equals(authHeader)) {
                chain.doFilter(request, response);
                return;
            }
            if (username != null
                    && SecurityContextHolder.getContext().getAuthentication() == null) {

                // 如果相信token中的数据，也就是签名token的secret的机制足够好
                // 这种情况下，可以不用再查询数据库，而直接采用token中的数据
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
//
//                boolean hasPermission = false;
//
//                for (GrantedAuthority ga : userDetails.getAuthorities()) {
//                    if (ga instanceof MyGrantedAuthority) {
//                        MyGrantedAuthority urlGrantedAuthority = (MyGrantedAuthority) ga;
//                        String url = urlGrantedAuthority.getUrl();
//                        String method = urlGrantedAuthority.getMethod();
//                        AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
//                        if (matcher.matches(request)) {
//                            //当权限表权限的method为ALL时表示拥有此路径的所有请求方式权利。
//                            if (method.equals(request.getMethod()) || "ALL".equals(method)) {
//                                hasPermission = true;
//                                break;
//                            }
//                        }
//                    }
//                }

                if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication
                        = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                            request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }

        chain.doFilter(request, response);
    }
}
